package com.hama.iotrust.common.atmosphere;

import java.util.concurrent.CountDownLatch;

import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hama.iotrust.common.atmosphere.SubscribeAction;
import com.hama.iotrust.common.atmosphere.SubscribeUtil;

@Controller
public class SubscribeAction {

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(SubscribeAction.class);

    private void suspend(final AtmosphereResource resource, final String path) {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        resource.addEventListener(new AtmosphereResourceEventListenerAdapter() {

            @Override
            public void onSuspend(AtmosphereResourceEvent event) {
                countDownLatch.countDown();
                resource.removeEventListener(this);
                logger.debug("New Subscribe : {} {} {}", path, resource.transport(), resource.session().getId());
            }
        });
        resource.getResponse().setCharacterEncoding("UTF-8");
        resource.suspend();
        SubscribeUtil.getBroadcaster(path).addAtmosphereResource(resource);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void onMessage(String message) {
        logger.debug(message);
    }

    @RequestMapping(value = "/subscribe/{path}")
    @ResponseBody
    public void warn(AtmosphereResource atmosphereResource, @PathVariable String path) {
        this.suspend(atmosphereResource, "/"+path);
    }

}
